const baseUrl = 'https://wechat.lychix.com/api/'; //测试环境

function promiseHelp(resolve, reject) {
    return {
        success(resp) {
            resolve(resp);
        },
        fail(err) {
            reject(err);
        }
    };
}

function promiseMethod(methodName) {
    return function (obj = {}) {
        return new Promise((resolve, reject) => {
            const option = promiseHelp(resolve, reject);
            Object.assign(option, obj);
            wx[methodName](option);
        });
    };
}



let isTokenRefreshing = false // 标识 token 刷新状态
let failedRequests = [] // 存储因为 token 刷新而挂起的请求
const util = {
    login: promiseMethod("login"),
    authorize: promiseMethod("authorize"),
    getSetting: promiseMethod("getSetting"),
    openSetting: promiseMethod("openSetting"),
    scanCode: promiseMethod("scanCode"),
    isRegister() {
        //是否注册登录了
        let userInfo = util.getUserInfo();
        if (userInfo.phone) {
            return userInfo;
        } else {
            return false
        }
    },
    objectToUrlParams(obj) {
        return Object.keys(obj).map(key => `${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`).join('&');
    },
    //上传图片
    uploadFile(file, url, callback) {
        wx.showLoading({
            title: '上传中...',
            mask: true
        });
        wx.uploadFile({
            url: baseUrl + url,
            filePath: file,
            header: {

            },
            name: 'upload-file',
            formData: {},
            success: (res) => {
                wx.hideLoading();
                let data = JSON.parse(res.data);
                if (data.code == 0) {
                    callback && callback(data);
                } else {
                    wx.showToast({
                        title: data.msg,
                        icon: 'none'
                    });
                }
            },
            fail(err) {
                wx.hideLoading();
                wx.showToast({
                    title: '网络异常！刷新后重试！',
                    icon: 'none'
                });
            }
        })
    },
    //多张图片上传
    uploadMutiple({
        file,
        url,
        name,
        header
    }) {
        return new Promise((resolve, reject) => {
            wx.uploadFile({
                url: baseUrl + url,
                filePath: file,
                header: header || {},
                name: name || 'file',
                formData: {},
                success: (res) => {
                    wx.hideLoading();
                    let data = JSON.parse(res.data);
                    if (data.code == 0) {
                        resolve({
                            state: true,
                            data: data
                        });
                    } else {
                        resolve({
                            state: false,
                            msg: data.msg
                        });
                    }
                },
                fail(err) {
                    resolve({
                        state: false,
                        msg: err
                    });
                }
            })
        })
    },
    openPdf(url) {
        this.downloadFile(url, (filepath) => {
            wx.openDocument({  
                filePath: filepath, // 替换为你的临时文件路径  
                fileType: 'pdf', // 指定文件类型为PDF  
                success: function(res) {  
                  // 打开文档成功  
                },  
                fail: function(err) {  
                  // 处理打开失败的情况  
                }  
            });
        });
    },
    saveFile(url) {
        this.downloadFile(url, (filepath) => {
            // 获取全局唯一的文件管理器  
            const fs = wx.getFileSystemManager();
            // 保存文件到本地  
            fs.saveFile({  
                tempFilePath: filepath, // 临时文件路径  
                success: function(res) {  
                    console.log('文件保存成功，保存路径为：', res.savedFilePath);
                    wx.showToast({
                        title: '保存成功！',
                        icon: 'none'
                    });
                },  
                fail: function(err) {  
                    console.error('文件保存失败：', err);  
                    wx.showToast({
                        title: '保存失败！',
                        icon: 'none'
                    });
                }  
            });
        });
    },
    downloadFile(url, callback) {
        wx.showLoading({
          title: '加载中',
        })
        url = url.indexOf('http') === -1 ? baseUrl + url : url;
        wx.downloadFile({
            url: url, // 文件的URL地址  
            success: function (res) {  
                wx.hideLoading();
              if (res.statusCode === 200) {  
                var tempFilePath = res.tempFilePath; // 临时文件路径 
                if (callback) callback(tempFilePath);
              } else { 
                wx.showToast({
                    title: '文件下载失败！',
                    icon: 'none'
                });
              }  
            },  
            fail: function (err) {  
                wx.hideLoading();
                wx.showToast({
                    title: '文件下载失败！',
                    icon: 'none'
                });
            }  
        });
    },

    copyText(txt) {
      wx.setClipboardData({
        data: txt,
        success: function (res) {
          wx.showToast({
            title: '检测码复制成功',
          })
        }
      })
    },

    downloadImage(url) {
      return new Promise((resolve, reject) => {
        wx.downloadFile({
          url: url,
          success: function (res) {
            if (res.statusCode === 200) {
              resolve(res.tempFilePath);
            } else {
              reject('下载失败');
            }
          },
          fail: function (err) {
            reject(err);
          }
        });
      });
    },

    async batchDownloadImages(imageUrls) {
      try {
        const tempFilePaths = await Promise.all(imageUrls.map(url => this.downloadImage(url)));
        tempFilePaths.forEach(tempFilePath => {
          wx.saveImageToPhotosAlbum({
            filePath: tempFilePath,
            success: function () {
              console.log('保存成功');
            },
            fail: function (err) {
              console.log('保存失败：', err);
            }
          });
        });
      } catch (error) {
        console.log('下载失败：', error);
      }
    },

    parseQueryString(url) {
        if (!url) {
            return {}
        }
        return JSON.parse('{"' + decodeURIComponent(url).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') + '"}')
    },
    loginCode(obj, resolve, reject, callback) {
        util.login().then((wxres) => {
            //登录
            util.http({
                url: 'v1/mini/session',
                data: {
                    code: wxres.code
                },
                method: "post",
                header: {
                    'content-type': 'application/json',
                }
            }).then((result) => {
                callback && callback(result)
            }).catch((err) => {
                reject(err);
            })
        }).catch((err) => {
            reject(err);
        })
    },
    refreshToken(obj, resolve, reject) {
        // 获取存储的 refreshToken 发送请求刷新 token
        if (isTokenRefreshing) {
            return failedRequests.push({
                obj,
                resolve,
                reject
            });
        }
        // token 失效
        // wx.removeStorageSync('UserInfo');

        isTokenRefreshing = true;

        //获取code
        util.login().then((wxres) => {
            //登录
            util.http({
                url: 'v1/mini/session',
                data: {
                    code: wxres.code
                },
                method: "post",
                header: {
                    'content-type': 'application/json',
                }
            }).then((result) => {
                if (result.data.code == 0 && result.data.data && result.data.data.token) {
                    util.setUserInfo({
                        token: result.data.data.token,
                    });
                    util.getMysqlUser().then((mysql) => {
                        let userInfo = util.getUserInfo();
                        let token = userInfo.token;

                        // console.log('重新筛选请求')
                        failedRequests.forEach((itemNode) => {
                            (function (item) {
                                if (!item.obj.header) {
                                    item.obj.header = {};
                                }
                                if (item.obj.header && item.obj.header.Authorization) {
                                    item.obj.header.Authorization = 'Bearer ' + token
                                }
                                util.http(item.obj).then((res) => item.resolve(res)).catch((err) => item.reject(err))
                            })(itemNode);

                        });
                        failedRequests = [];

                        // console.log('首个失败的请求发起', obj)
                        if (obj.header && obj.header.Authorization) {
                            obj.header.Authorization = 'Bearer ' + token
                        }
                        util.http(obj).then((res) => resolve(res)).catch((err) => reject(err))
                    }).finally(() => {
                        isTokenRefreshing = false;
                    });
                } else {
                    resolve(result)
                }

            }).catch((err) => {
                reject(err);
            })
        }).catch((err) => {
            reject(err);
        })
    },
    http(obj) {
        return new Promise((resolve, reject) => {
            if (obj.url.indexOf(baseUrl) == -1) {
                obj.url = baseUrl + obj.url;
            }
            Object.assign(obj, {
                success(res) {
                    //登录失败或者token过期 刷新token 
                    if (res.data && res.data.code == 401) {
                        util.refreshToken(obj, resolve, reject);
                    } else {
                        resolve(res);
                    }
                },
                fail(res) {
                    reject(res);
                }
            })
            wx.request(obj);
        });
    },
    //取cookie 用户信息
    getUserInfo() {
        return wx.getStorageSync('UserInfo') || {};
    },
    getNode(array, key, value) {
        for (let index = 0; index < array.length; index++) {
            const element = array[index];
            if (element[key] == value) {
                return index;
            }
        }
        return -1;
    },
    //获取用户信息
    getMysqlUser() {
        return new Promise((resolve, reject) => {
            util.http.get("v1/mini/userinfo", {}).then((res) => {
                // console.log(res);
                if (res.data.code == 0) {
                    util.setUserInfo(res.data.data);
                }
                resolve(res.data);
            }).catch((err) => {
                reject(err);
            });
        })
    },
    //存cookie 用户信息
    setUserInfo(obj) {
        wx.setStorageSync('UserInfo', Object.assign(util.getUserInfo(), obj));
    },
    getAddress() {
        return wx.getStorageSync('Address') || {};
    },
    //存cookie 用户信息
    setAddress(obj) {
        wx.setStorageSync('Address', Object.assign(util.getAddress(), obj));
    },
    truncateString(str, len) {
        return str.slice(0, len); // 截取前300个字符
    },
}

util.http.get = function (url = "", data = {}, header = {}) {
    return new Promise((resolve, reject) => {
        let userInfo = util.getUserInfo();
        let token = userInfo.token;
        const tokenHeader = Object.assign(header, {
            Authorization: 'Bearer ' + token
        })
        const headers = {
            'content-type': 'application/json',
        }
        let obj = {
            url,
            data,
            method: "GET",
            header: Object.assign(headers, tokenHeader)
        }
        if (!token) {
            util.refreshToken(obj, resolve, reject);
        } else {
            util.http(obj).then((res) => {
                resolve(res)
            }).catch((err) => {
                reject(err);
            });
        }
    })
};

util.http.post = function (url = "", data = {}, header = {}) {
    return new Promise((resolve, reject) => {
        let userInfo = util.getUserInfo();
        let token = userInfo.token;
        const tokenHeader = Object.assign(header, {
            Authorization: 'Bearer ' + token
        })
        const headers = {
            'content-type': 'application/json;charset=utf-8',
        }
        let obj = {
            url,
            data,
            method: "POST",
            header: Object.assign(headers, tokenHeader)
        }
        if (!token) {
            util.refreshToken(obj, resolve, reject);
        } else {
            util.http(obj).then((res) => {
                resolve(res)
            }).catch((err) => {
                reject(err);
            });
        }
    })
};

util.http.delete = function (url = "", data = {}, header = {}) {
    return new Promise((resolve, reject) => {
        let userInfo = util.getUserInfo();
        let token = userInfo.token;
        const tokenHeader = Object.assign(header, {
            Authorization: 'Bearer ' + token
        })
        const headers = {
            'content-type': 'application/json',
        }
        let obj = {
            url,
            data,
            method: "DELETE",
            header: Object.assign(headers, tokenHeader)
        }
        if (!token) {
            util.refreshToken(obj, resolve, reject);
            let isTps = userInfo.isTps;
            if (isTps && isTps == 1) {
                util.setUserInfo({
                    isTps: 1,
                });
            }
        } else {
            util.http(obj).then((res) => {
                resolve(res)
            }).catch((err) => {
                reject(err);
            });
        }
    })
};


const commonMixin = Behavior({
    data: {
        navHeight: 60,
        commonFile: 'https://wechat.lychix.com/xcxfile/'
    },
    pageLifetimes: {
        // 组件所在页面的生命周期函数
        show: function () {

        },
    },
    lifetimes: {
        // 生命周期函数，可以为函数，或一个在methods段中定义的方法名
        // 在组件实例进入页面节点树时执行
        attached: function () {

        },
        // 在组件实例被从页面节点树移除时执行
        detached: function () {}
    },
    methods: {

        //输入框改变值
        changeInput(e) {
            let changeKey = e.currentTarget.dataset.fields
            this.setData({
                [changeKey]: e.detail.value
            })
        },
        // radio switch 类的
        changeCheckbox(e) {
            let changeKey = e.currentTarget.dataset.fields
            this.setData({
                [changeKey]: e.detail
            })
        },
        redTo(event) {
            const {
                url
            } = event.currentTarget.dataset;
            url && wx.redirectTo({
                url
            });
        },
        navToUrl(url) {
          if (url) {
            console.log(url);
            if (url == '/pages/index/index' || url == '/pages/appointment/index' || url == '/pages/report/index' || url == '/pages/my/index') {
              wx.switchTab({
                url: url,
              });
            } else {
              wx.navigateTo({
                  url
              });
            }
          }
        },
        navTo(event) {
          const {
              url
          } = event.currentTarget.dataset;
          this.navToUrl(url);
        },
        switchTabBar(event) {
            const {
                url
            } = event.currentTarget.dataset;
            url && wx.switchTab({
                url
            });
        },
        goHome() {
            this.redToUrl("/pages/index/index");
        },
        goBack() {
            wx.navigateBack();
        },
        navigateBack() {
            wx.navigateBack();
        },
        /**
         * [ArrayToObject 数组转对象]
         * @param {[type]} arr [原始数据]
         * @param {[type]} key [对应简明]
         * 
         * // 使用方法
            var arr = [1,2,3,4];
            console.log(ArrayToObject(arr,'url'));
         */
        ArrayToObject(arr, key) {
            let json = [];
            for (let i = 0; i < arr.length; i++) {
                var obj = {};
                obj[key] = arr[i];
                json.push(obj);
            }
            return json;
        },
    }
});

import Toast from '@vant/weapp/toast/toast';

//全局设置间隔
Toast.setDefaultOptions({
    duration: 2500
});

import Dialog from '@vant/weapp/dialog/dialog';
module.exports = {
    util,
    Toast,
    Dialog,
    commonMixin
}
